<template>
  <a-modal
    :visible="visible"
    :width="1000"
    okText="提交"
    cancelText="取消"
    :title="title"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    @cancel="closeModal()"
    @ok="handleSubmit"
  >
    <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }">
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 产品分类 </span>
        </template>
        <a-button type="primary" @click="handleAddClassify"
          >增加分类归类</a-button
        >
        <div v-for="(item, index) in addClassifyList" :key="index">
          <a-space>
            <a-cascader
              :options="classifyList"
              style="width: 240px"
              :allowClear="true"
              v-model="item.value"
              placeholder="请选择产品分类"
            />
            <a-icon
              class="dynamic-delete-button"
              type="minus-circle-o"
              @click="handleRemoveClassify(index)"
            />
          </a-space>
        </div>
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 案例名称 </span>
        </template>
        <a-input
          autocomplete="off"
          v-model="productName"
          :maxLength="32"
          placeholder="请输入案例名称，限32位汉字以内"
        />
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 案例主图片 </span>
        </template>
        <a-space class="main_picture">
          <ImageUpload
            v-model="largeScreenPicture"
            uploadTextHtml="大屏APP封面图<br/>建议尺寸：<br/>540*540像素"
          ></ImageUpload>
          <ImageUpload
            v-model="appPicture"
            uploadTextHtml="手机APP封面图<br/>建议尺寸：540*540像素"
          ></ImageUpload>
          <ImageUpload
            v-model="appletPicture"
            uploadTextHtml="小程序封面图<br/>建议尺寸：690*300像素"
          ></ImageUpload>
        </a-space>
        <div>
          <a-space align="start" class="upload_detail">
            <!-- <ImageUploadList
                  :limit="9"
                  :multiple="true"
                  :isCustomBtn="true"
                  @change="handleDetailChange">
                  <a-button type="primary"> 上传详情图片 </a-button>
                </ImageUploadList>
                *建议尺寸：1280*670像素 -->
            <ImageUploadList
              :limit="1000"
              :multiple="true"
              v-model="productDetailsList"
              uploadTextHtml="轮播图建议尺寸1280*760像素或等比例大小，图片大小在2M以内"
              @urls="handleDetailChange"
            >
            </ImageUploadList>
          </a-space>
        </div>
      </a-form-item>
      <a-form-item label="全景图">
        <a-radio-group :options="yesNo"
          v-model="enablePanorama"></a-radio-group>
      </a-form-item>
      <a-form-item label="案例链接">
        <a-input type="text" placeholder="请输入链接，如www.baidu.com/" v-model="productUrl"/>
      </a-form-item>
      <a-form-item label="基本信息">
        <div class="product_spec table">
          <div class="tbody">
            <div class="tr" v-for="(item, index) in productSpec" :key="index">
              <div class="th">
                <input
                  type="text"
                  maxlength="10"
                  v-model="item.left.value"
                  :placeholder="item.left.placeholder"
                  @change="handleChangeProductSpec"
                />
              </div>
              <div class="td">
                <input
                  type="text"
                  maxlength="10"
                  v-model="item.right.value"
                  :placeholder="item.right.placeholder"
                  @change="handleChangeProductSpec"
                />
              </div>
              <div class="icon">
                <a-icon
                  class="dynamic-delete-button"
                  type="minus-circle-o"
                  @click="handleRemoveProductSpec(index)"
                />
              </div>
            </div>
          </div>
          <div class="tfoot">
            <div class="tr">
              <div class="td" colspan="2">
                <a href="javascript:;" @click="handleAddProductSpec"
                  >点击增加规格</a
                >
              </div>
            </div>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="产品简介">
        <a-input
          placeholder="请输入你的阶段性工作目标，限38位汉字以内"
          v-model="productIntroduction"
          :maxLength="38"
        ></a-input>
        <!-- <tinymce-editor v-model="productIntroduction"></tinymce-editor> -->
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 排序 </span>
        </template>
        <a-input-number
          :precision="0"
          :min="0"
          v-model="sort"
          :maxLength="4"
          placeholder="请输入4位以内的整数"
          style="width: 160px"
        />
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 是否显示 </span>
        </template>
        <a-radio-group
          :options="statusList"
          v-model="showStatus"
        ></a-radio-group>
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 设为推荐 </span>
        </template>
        <a-radio-group :options="yesNo"
          v-model="enableRecommend"></a-radio-group>
      </a-form-item>
      <a-form-item>
        <template slot="label">
          <span class="ant-form-item-required"> 展示平台 </span>
        </template>
        <a-checkbox-group :options="platformList" v-model="showPlatform">
        </a-checkbox-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import deepCopy from "@/utils/deepCopy.js";
import {
  showPlatformList,
  showStatusList,
  showSpecList,
  yesOrNo
} from "@/utils/dictData";
import ImageUpload from "@/components/antBase/ImageUpload";
//import ImageUploadList from "./UploadImage";
//import ImageUploadList from '../../../libraryManagement/galleryList/components/UploadImage2';
import ImageUploadList from '@/components/form/UploadImage';

export default {
  components: {
    ImageUpload,
    ImageUploadList,
  },
  props: {
    record: {
      type: Object,
      default() {
        return {};
      },
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    title() {
      return this.record.id ? "修改产品" : "新增产品";
    },
  },
  data() {
    return {
      // 产品分类
      classifyList: [],
      // 添加分类归类
      addClassifyList: [],
      // 产品名称
      productName: "",
      // 是否全景图
      enablePanorama: 0,
      // 案例链接
      productUrl: '',
      // 产品规格
      productSpec: deepCopy(showSpecList),
      // 产品简介
      productIntroduction: "",
      // 排序
      sort: 0,
      // 显示状态
      statusList: showStatusList,
      showStatus: 1,
      // 设为推荐
      yesNo: yesOrNo,
      enableRecommend: 0,
      // 展示平台
      platformList: showPlatformList,
      showPlatform: [],
      // 上传详情图片
      productDetailsList: "",
      // 产品主图片
      largeScreenPicture: "", // 大屏APP封面图
      appPicture: "", // APP封面图
      appletPicture: "", // 小程序封面图
      isUploadDetailMessage: false,
      // 图库产品
      productSpecList: [],
      // 提交表单数据
      formData: {
        caseClassificationIdList: [], // 图库分类id集合
        caseProductName: "", //	图库产品名称
        largeScreenPicture: "", // 大屏APP封面图
        appPicture: "", // APP封面图
        appletPicture: "", // 小程序封面图
        enablePanorama: 0, // 是否全景图（0.,否 1.是）
        caseProductUrl: '', // 案例链接
        caseProductPictures: [], // 图库产品图片url集合,
        caseProductDescribe: "", // 图库产品简介
        sort: 0, // 排序
        enableShow: "", // 是否展示（0.,否 1.是）
        enableRecommend: 0, // 设为推荐（0.,否 1.是）
        exhibitionPlatform: "", // 展示平台 (多个平台用,隔开)
      },
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetData();
        this.getDetail();
      }
    },
  },
  created() {
    this.getClassifyList();
  },
  methods: {
    resetData() {
      this.addClassifyList = [];
      this.productName = "";
      this.largeScreenPicture = ""; // 大屏APP封面图
      this.appPicture = ""; // APP封面图
      this.appletPicture = ""; // 小程序封面图
      this.enablePanorama = 0
      this.productUrl = ''
      this.productDetailsList = "";
      this.productSpec = deepCopy(showSpecList);
      console.log("showSpecList", deepCopy(showSpecList));
      this.productIntroduction = "";
      this.sort = 0;
      this.showStatus = 1;
      this.enableRecommend = 0;
      this.showPlatform = [];
    },
    formatClassifyList(data) {
      let tmpData = [];
      for (let i = 0; i < data.length; i++) {
        let item = {
          label: data[i].caseName,
          value: data[i].id,
        };
        if (data[i].children && data[i].children.length > 0) {
          item["children"] = this.formatClassifyList(data[i].children);
        }
        tmpData.push(item);
      }
      return tmpData;
    },
    // 产品分类
    async getClassifyList() {
      let res = await this.$get("/cases/classification/list");
      console.log(res);
      if (res && res.returnCode == 1000 && res.dataInfo) {
        // this.classifyList = this.formatClassifyList(res.dataInfo||[]);
        let tmpData = this.formatClassifyList(res.dataInfo || []);
        this.classifyList = tmpData.filter((item) => {
          return item.children && item.children.length > 0;
        });
        console.log("this.classifyList", this.classifyList);
      }
    },
    // 格式化产品属性
    // formatQuotedPriceListData(arr){
    //   var map = {}
    //   var dest = []
    //   for (var i = 0; i < arr.length; i++) {
    //     var ai = arr[i]
    //     if (!map[ai.quotedPriceId]) {
    //       dest.push({
    //         id: ai.quotedPriceId,
    //         options: [ai]
    //       })
    //       map[ai.quotedPriceId] = ai
    //     } else {
    //       for (var j = 0; j < dest.length; j++) {
    //         var dj = dest[j]
    //         if (dj.id === ai.quotedPriceId) {
    //           dj.options.push(ai)
    //           break
    //         }
    //       }
    //     }
    //   }
    //   return dest;
    // },
    formatCasesClassificationList(data = []) {
      let tmpData = [];
      data.forEach((item) => {
        if (item) {
          let arr = item.split(",");
          if (arr.length > 0) {
            let tmpData2 = [];
            arr.forEach((item) => {
              tmpData2.push(item.trim());
            });
            tmpData2.splice(0, 1);
            tmpData.push(tmpData2);
          }
        }
      });
      return tmpData;
    },
    async getDetail() {
      let id = this.record.id;
      if (!id) {
        return;
      }
      let res = await this.$get("/cases/product/query", { id });
      if (res && res.returnCode == 1000) {
        let tmpObj = res.dataInfo;
        if (
          tmpObj.caseClassificationList &&
          tmpObj.caseClassificationList.length > 0
        ) {
          tmpObj.caseClassificationList = this.formatCasesClassificationList(
            tmpObj.caseClassificationList
          );
          this.addClassifyList = [];
          tmpObj.caseClassificationList.forEach((item) => {
            this.addClassifyList.push({
              value: item || [],
            });
          });
        }
        console.log("this.addClassifyList", this.addClassifyList);
        this.productName = tmpObj.caseProductName;
        this.largeScreenPicture = tmpObj.largeScreenPicture;
        this.appPicture = tmpObj.appPicture;
        this.appletPicture = tmpObj.appletPicture;
        this.enablePanorama = tmpObj.enablePanorama;
        this.productUrl = tmpObj.caseProductUrl;
        this.productIntroduction = tmpObj.caseProductDescribe;
        this.sort = tmpObj.sort;
        this.showStatus = tmpObj.enableShow;
        this.enableRecommend = tmpObj.enableRecommend;
        this.quotedPrice = tmpObj.quotedPrice;
        this.caseQuotedPriceList = tmpObj.caseQuotedPriceList;
        this.productDetailsList = tmpObj.caseProductPictures;
        this.showPlatform =
          tmpObj.exhibitionPlatform &&
          tmpObj.exhibitionPlatform.split(",").map((item) => {
            return parseInt(item);
          });
        if (
          tmpObj.caseProductInfoList &&
          tmpObj.caseProductInfoList.length > 0
        ) {
          this.productSpec = [];
          tmpObj.caseProductInfoList.forEach((item) => {
            // productSpecList
            this.productSpec.push({
              left: {
                placeholder: "请输入",
                value: item.infoName,
              },
              right: {
                placeholder: "请输入",
                value: item.infoValue,
              },
            });
          });
          this.handleChangeProductSpec();
        }
      }
    },
    // 添加分类归类
    handleAddClassify() {
      if (this.addClassifyList.length < 3) {
        this.addClassifyList.push({
          value: [],
        });
      } else {
        this.$message.error("最多添加三个分类");
      }
    },
    // 移出分类归类
    handleRemoveClassify(index) {
      this.addClassifyList.splice(index, 1);
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener("load", () => callback(reader.result));
      reader.readAsDataURL(img);
    },
    // 上传详情图片
    handleDetailChange(info) {
      console.log("urls", info);
      // this.productDetailsList = info;
    },
    // 大屏APP封面图
    handleChange0(info) {
      this.largeScreenPicture = info;
    },
    // 手机APP封面图
    handleChange1(info) {
      this.appPicture = info;
    },
    // 小程序封面图
    handleChange2(info) {
      this.appletPicture = info.file.response.url;
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("你只能上传png或jpg图片!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图像必须小于2MB！");
      }
      return isJpgOrPng && isLt2M;
    },
    closeModal(freshTable) {
      this.resetData();
      this.$emit("cancel", freshTable);
    },
    // 添加产品规则
    handleAddProductSpec() {
      this.productSpec.push({
        left: {
          placeholder: "请输入",
          value: "",
        },
        right: {
          placeholder: "请输入",
          value: "",
        },
      });
    },
    handleRemoveProductSpec(index) {
      this.productSpec.splice(index, 1);
      this.handleChangeProductSpec();
    },
    handleChangeProductSpec() {
      let caseProductSpecList = [];
      if (this.productSpec.length > 0) {
        this.productSpec.forEach((item) => {
          if (item.left.value && item.right.value) {
            caseProductSpecList.push({
              infoName: item.left.value,
              infoValue: item.right.value,
            });
          }
        });
      }
      this.productSpecList = caseProductSpecList;
    },
    // 提交
    handleSubmit() {
      let addClassifyList = this.addClassifyList
        .map((item) => {
          return item.value.join(",");
        })
        .filter((item) => {
          return item;
        });
      // addClassifyList=Array.from(new Set(addClassifyList));
      if (!addClassifyList.length) {
        this.$message.error("请选择产品分类");
        return;
      }
      if (addClassifyList.length > 3) {
        this.$message.error("最多添加三个分类");
        return;
      }
      console.log(
        Array.from(new Set(addClassifyList)).length,
        addClassifyList.length
      );
      if (
        Array.from(new Set(addClassifyList)).length != addClassifyList.length
      ) {
        this.$message.error("分类存在重复");
        return;
      }
      if (!this.productName) {
        this.$message.error("请输入产品名称，限32位汉字以内");
        return;
      }
      if (!this.largeScreenPicture) {
        this.$message.error("请上传大屏APP封面图");
        return;
      }
      if (!this.appPicture) {
        this.$message.error("请上传APP封面图");
        return;
      }
      if (!this.appletPicture) {
        this.$message.error("小程序封面图");
        return;
      }
      if (!this.sort && this.sort !== 0) {
        this.$message.error("请输入排序");
        return;
      }
      if (this.showStatus === "") {
        this.$message.error("请选择是否显示");
        return;
      }
      if (this.enableRecommend === "" || this.enableRecommend === undefined || this.enableRecommend === null) {
        this.$message.error('请选择是否设为推荐')
        return
      }
      if (!this.showPlatform.length) {
        this.$message.error("请选择展示平台");
        return;
      }
      console.log("this.productDetailsList", this.productDetailsList);
      this.formData = {
        caseClassificationIdList: addClassifyList, // 图库分类id集合
        caseProductName: this.productName, //	图库产品名称
        largeScreenPicture: this.largeScreenPicture, // 大屏APP封面图
        appPicture: this.appPicture, // APP封面图
        appletPicture: this.appletPicture, // 小程序封面图
        enablePanorama: this.enablePanorama, // 是否全景图（0.,否 1.是）
        caseProductUrl: this.productUrl, // 图库产品链接
        caseProductPictures: this.productDetailsList, // 案例产品图片url集合,多个用,隔开,
        caseProductInfoList: this.productSpecList, // 图库产品规格属性集合
        caseProductDescribe: this.productIntroduction, // 图库产品简介
        sort: this.sort, // 排序
        enableShow: this.showStatus, // 是否展示（0.,否 1.是）
        enableRecommend: this.enableRecommend, // 设为推荐（0.,否 1.是）
        exhibitionPlatform: this.showPlatform.join(","), // 展示平台 (多个平台用,隔开)
      };
      if (this.record && this.record.id) {
        this.formData.id = this.record.id;
      }
      console.log(this.formData);
      let add_url = "/cases/product/add";
      let update_url = "/cases/product/update";
      let url = this.record.id ? update_url : add_url;
      this.$post(url, this.formData).then((res) => {
        if (res && res.returnCode === 1000) {
          this.$message.success("保存成功！");
          this.closeModal(true);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
::-webkit-input-placeholder {
  /* WebKit browsers */
  color: #ccc;
  font-size: 14px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
.avatar_img {
  max-width: 104px;
}
.main_picture {
  /deep/ .ant-upload {
    width: 104px !important;
    height: 104px !important;
    .anticon {
      svg {
        font-size: 24px;
        color: #016bff;
      }
    }
    img {
      //display: block;
      max-width: 100%;
      max-height: 100%;
    }
    .ant-upload-text {
      font-size: 12px;
    }
  }
}
// .table{
//   border: 1px solid #E6E6E6;
//   //border-radius: 4px;
//   tbody{
//     th,td{
//       border: 1px solid #E6E6E6;
//       padding:0 10px;
//       white-space: nowrap;
//       input[type=text],
//       input[type=number]{
//         border:none;
//         outline:none;
//         box-sizing: border-box;
//         height:40px;
//       }
//       input[type=number]{
//         line-height: 1;
//       }
//     }
//     th{
//       input[type=text]{
//         text-align: center;
//       }
//     }
//     td{
//       input[type=text]{

//       }
//     }
//   }
//   tfoot{
//     td{
//       background:#F5F5F5;
//       text-align: center;
//       a{
//         font-size:12px;
//       }
//     }
//   }
// }
.table {
  border-right: 1px solid #e6e6e6;
  border-bottom: 1px solid #e6e6e6;
  //border-radius: 4px;
  .tbody {
    .tr {
      display: flex;
      align-items: center;
      position: relative;
      .th,
      .td {
        border-top: 1px solid #e6e6e6;
        border-left: 1px solid #e6e6e6;
        padding: 0 10px;
        white-space: nowrap;
        input[type="text"],
        input[type="number"] {
          border: none;
          outline: none;
          box-sizing: border-box;
          height: 40px;
        }
        input[type="number"] {
          line-height: 1;
        }
      }
      .th {
        input[type="text"] {
          text-align: center;
        }
      }
      .td {
        flex: 1;
        input[type="text"] {
          width: 100%;
        }
      }
      .icon {
        position: absolute;
        right: -0.3rem;
      }
    }
  }
  .tfoot {
    .tr {
      .td {
        border-top: 1px solid #e6e6e6;
        border-left: 1px solid #e6e6e6;
        background: #f5f5f5;
        text-align: center;
        a {
          font-size: 12px;
        }
      }
    }
  }
}
.quotationAttr {
  margin-bottom: 10px;
  tbody {
    tr:last-child {
      text-align: center;
    }
  }
  /deep/ .ant-select-selection {
    border: none;
    outline: none;
  }
  .ant-select-open .ant-select-selection {
    box-shadow: none;
  }
  input {
    width: 60px;
    text-align: center;
  }
}
</style>
